import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { redisUtils as redis } from 'src/utils/redis';
import { Config } from 'src/config';
import { getUser } from 'src/utils/getUser';

@Injectable()
export class AuthService {
  constructor(private readonly jwt: JwtService) {}

  generate({
    phone,
    username,
    email,
    id,
  }: {
    phone: string;
    username: string;
    email: string;
    id: number;
  }) {
    const token =
      'Bearer ' +
      this.jwt.sign(
        { phone, username, email, id },
        { secret: Config.token.secret },
      );
    redis.set(
      `${Config.token.prefix}${token}`,
      id.toString(),
      Config.token.expiresIn,
    );
    return token;
  }

  async verify(token: string) {
    const user = await getUser(token);
    return user !== '游客';
  }

  async del(token: string) {
    const user = await getUser(token);
    await redis.del(`${Config.token.prefix}${token}`);
    return user ? `用户：${user}已退出登录` : '该用户未登录';
  }
}
